// @Author miaoqing
// @Date 2024/03/28 18:24:00
// @Desc
package logic

import (
	"core/command"
	"core/component/logger"
	"core/component/router"
	"core/network"
	"runtime/debug"
	"time"
)

type Client struct {
	*network.NetConn
	router     *router.Router
	userID     uint64
	remoteAddr string
}

func (c *Client) Init() {
	c.router = router.NewRouter()
	c.registerHandler()
}

func (c *Client) registerHandler() {
	//c.router.Register()
}

func (c *Client) OnMessage(data []byte) {
	defer func() {
		if err := recover(); err != nil {
			logger.Error("[server_client] panic ", err, "\n", string(debug.Stack()))
		}
	}()
	now := time.Now()
	msgID, err := c.router.Route(data)
	if err != nil {
		return
	}
	if command.Command(msgID).String() != "CSHeartBeat_Gateway" {
		logger.Debugf("[gateway] 已处理玩家:%v 消息ID::%v execTime:%v", c.userID, command.Command(msgID).String(), time.Since(now))
	}
}

func (c *Client) OnClose() {
	logger.Info("EOOOOOOOOFF")
}

func (c *Client) OnConnect() {
	c.remoteAddr = c.RemoteAddr().String()
	logger.Infof("[连接] 建立连接 local:%s remote:%s ConnID:%v", c.LocalAddr(), c.RemoteAddr().String(), c.ConnID)
	clientMgrGetMe().addClients(c.ConnID, c)
}

func (c *Client) Marshal(msgID uint16, msg interface{}) ([]byte, error) {
	c.router.Marshal(msgID, msg)
	return nil, nil
}

// sendMsg 异步发送数据包
func (cli *Client) sendMsg(cmd command.Command, msg interface{}) bool {
	return cli.AsyncSend(uint16(cmd), msg)
}
